package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Macross
 * @Type JwtInterceptor.java
 * @Desc 鉴权拦截器
 * @date 2019/12/25 20:46
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(header)) {
            if (header.startsWith("bearer ")) {
                String token = header.substring(7);
                Claims claims = jwtUtil.parseToken(token);
                if (claims != null){
                    request.setAttribute("claims",claims);
                }
            }
        }
        return true;
    }
}
